<?php
/**
 *
 * @author Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 * @copyright (c) 2011.
 */

class PropertyController extends AppController {
    # Controller Name to be used
   var $name = 'Property';

  # Models to be used
   var $uses = array(
       'User',
       'Organisation',
       'Module',
       'Configuration',
       'PropertyItem',
       'PropertyItemDetail',
       'PropertyGroup',
       'Location',
       'PropertyGroupType',
       'PropertyGroupSubType'
   );
    # Helpers and components

   # set the layout to use
   var $layout = 'property_layout';
   
   # set the name of this module
   var $moduleName = 'Property Management';

   # Check the authenticity of the user
   function  beforeFilter() {
          parent::setUpGlobalConfig();  
          # Check the user validity
          if($this->Session->check('userSessionData')){
                 $loggedUser =  $this->Session->read('userSessionData');
                 $userData = $this->User->getUserById($loggedUser['id']);
                 $userModules = $userData['Module'];
                 $allowed = false;
                 foreach($userModules as $module){
                    if($module['name'] === $this->moduleName){
                        $allowed = true;
                    }
                 }
                 if(!$allowed){
                      $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
                 }
          }
          else{
                  $this->redirect('/');
          }
   }
   
   # Controller actions
   /**
    * This function displays all the users in the system
    * @name index
    * @param void
    * @return Array of data.
    * @access public
    */
   function index(){			
		$next_auto_increment = $this->PropertyItem->getNextAutoIncrement();
        
        $prpGroup = Hash::combine($this->PropertyGroup->find('all',array('conditions' => array('deleted'=>0),'fields'=>array('id','group_name'),'recursive'=>-1)),'{n}.PropertyGroup.id', '{n}.PropertyGroup');
        $jsonArr = array(array('name'=>'All','value'=>0));
        foreach($prpGroup as $key => $value){
            $jsonArr[] = array('name'=>$value['group_name'],'value'=>$value['id']);
        }

        $prpFieldGroup = $this->PropertyGroup->find('all',array(
                'fields'=>array('id','group_name','fields','group_code'),
                'conditions' => array('deleted'=>0),
                'contain'=>array(
                    'PropertyGroupType'=>array(
                        'fields'=>array('id','type_name'),
                        'conditions' => array('deleted'=>0),
                        'PropertyGroupSubType'=>array(
                            'fields'=>array('id','sub_type_name'),
                            'conditions' => array('deleted'=>0)
                        )
                    ),
                ),
                'recursive'=>2
            )
        );
        //debug($prpFieldGroup);
        $prpGroupData = array();
        foreach($prpFieldGroup as $value){
            $prpGroupData[$value['PropertyGroup']['id']]['id'] = $value['PropertyGroup']['id'];
            $prpGroupData[$value['PropertyGroup']['id']]['group_name'] = $value['PropertyGroup']['group_name'];
            $prpGroupData[$value['PropertyGroup']['id']]['group_code'] = $value['PropertyGroup']['group_code'];
            
            if($value['PropertyGroup']['fields']){
                $fields_arr = explode(',',$value['PropertyGroup']['fields']);
                foreach($fields_arr as $value_0){
                    $prpGroupData[$value['PropertyGroup']['id']]['fields'][] = $value_0;
                }
            }
            else{
                $prpGroupData[$value['PropertyGroup']['id']]['fields'] = array();
            }
            
            foreach($value['PropertyGroupType'] as $value_1){
                $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['id'] = $value_1['id'];
                $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['type_name'] = $value_1['type_name'];
                
                foreach($value_1['PropertyGroupSubType'] as $value_2){
                    $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['group_sub_type'][$value_2['id']]['id'] = $value_2['id'];
                    $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['group_sub_type'][$value_2['id']]['sub_type_name'] = $value_2['sub_type_name'];
                }
            }
            
        }
        
        $loc_data = Hash::combine($this->Location->find('all',array(
                'fields'=>array('id','location_name','location_code'),
                'conditions' => array('deleted'=>0),
                'recursive'=>-1
            )
        ),'{n}.Location.id', '{n}.Location');

       $reg_no_prefix = REG_NO_PREMIX;
        
        $this->set(compact('jsonArr','prpGroupData','loc_data','next_auto_increment','reg_no_prefix'));
   }

   
    /**
    * This function add all new properties 
    * @name add
    * @param void
    * @return Array of data.
    * @access public
    */
   function add(){			
    	$this->autoRender = false;
        $this->autoLayout = false;
        $model = $_POST['model'];
             # Check the model
             switch($model){
                case 'Property' :
                    
                    $upt_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                    $property_detail_id =  $_POST['property_detail_id'];
                	$loggedUser =  $this->Session->read('userSessionData');
                	$loggedUser_id = $loggedUser['id'];
                	$save_date = date('Y-m-d H:i:s');
                    
                    if($upt_id){ /** Edit*/
                		$this->PropertyItem->id = $upt_id;
                	}
                	else{ /** New*/
                		$this->PropertyItem->create();                            		
                	}
                    
                    # save the data
                	if($upt_id){ 
                		if($this->PropertyItem->save($this->request->data['PropertyItem'])){
                            //$this->request->data['PropertyItemDetail']['property_items_id'] = $upt_id;
                           $this->PropertyItemDetail->id = $property_detail_id;
                            if($this->PropertyItemDetail->save($this->request->data['PropertyItemDetail'])){
                                $next_auto_increment = $this->PropertyItem->getNextAutoIncrement();
                                return json_encode(array('code' => 0, 'next_auto_increment'=>$next_auto_increment, 'mesg' =>'Data Saved'));
                            }
                            else{
                                return json_encode(array('code' => 1, 'mesg' => 'Data Not Saved'));
                            }   
                    	}
                		else{
                			  return json_encode(array('code' => 1, 'mesg' => $this->PropertyItem->invalidFields()));
                		}  
                	}
                	else{
                		if($this->PropertyItem->saveAll($this->request->data)){
                		      $next_auto_increment = $this->PropertyItem->getNextAutoIncrement();
                   			  return json_encode(array('code' => 0, 'next_auto_increment'=>$next_auto_increment, 'mesg' => 'Data Saved'));
                		}
                		else{
                			  return json_encode(array('code' => 1, 'mesg' => $this->PropertyItem->invalidFields()));
                		}    
                	}
                        
                 break;
    
             }
   }
   
   
    /**
    * This function loads all the property for a grid table display
    * @name index
    * @param void
    * @return Array of data.
    * @access public
    */
   function getPropertyList(){			
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;
        
        //return json_encode(array('success' => false, 'total'=>0, 'page' => 1, 'rows' => array()));
        
        /**  Get posted data */
        $page =      isset($_POST['page']) ? $_POST['page'] : 1 ; /** The current page */
        $sortname =  isset($_POST['sortname']) ? $_POST['sortname'] : 'id' ; /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc' ; /** Sort order */
        $qtype =     isset($_POST['qtype']) ? $_POST['qtype'] : '' ; /** Search column */
        $search_query =     isset($_POST['query']) ? $_POST['query'] : '' ; /** Search string */
        $rp =        isset($_POST['rp']) ? $_POST['rp'] : 10 ;
        $filter =   isset($_POST['filter']) ? $_POST['filter'] : 0 ; /** Filter the property group */
        $limit = $rp;
        $start = ($page-1) * $rp;
        
        if($filter == 0){
            $condition_array = array('PropertyItem.deleted' => 0);
            if (!empty($search_query)){
                if($search_query == 'property_reg_no'){
                    $condition_array = array(
                       'PropertyItem.property_reg_no' => $search_query,
                       'PropertyItem.deleted' => 0
                     );
                }
                else{
                    $condition_array = array(
                       "PropertyItem.$qtype LIKE" => $search_query . '%',
                       'PropertyItem.deleted' => 0
                     );
                }
            }
        }
        else{
            $condition_array = array('PropertyItem.deleted' => 0, 'PropertyItem.property_group_id'=>$filter);
            if (!empty($search_query)){
                if($search_query == 'property_reg_no'){
                    $condition_array = array(
                       'PropertyItem.property_reg_no' => $search_query,
                       'PropertyItem.deleted' => 0,
                       'PropertyItem.property_group_id'=>$filter
                     );
                }
                else{
                    $condition_array = array(
                       "PropertyItem.$qtype LIKE" => $search_query . '%',
                       'PropertyItem.deleted' => 0,
                       'PropertyItem.property_group_id'=>$filter
                     );
                }
            }
        }
        
        $contain = array(
            /** 'PropertyItemDetail' => array(
                'fields'=>array('id','name')
             ),*/
             'PropertyGroup' => array(
                'fields'=>array('id','group_name')
             ),
             'Location' => array(
                'fields'=>array('id','location_name','location_code')
             ),
             'PropertyGroupType' => array(
                'fields'=>array('id','type_name')
             ),
             'PropertyGroupSubType' => array(
                'fields'=>array('id','sub_type_name')
             ),
        );
        $fields = array('PropertyItem.id','PropertyItem.property_reg_no','PropertyItem.name','PropertyItem.loc_region','PropertyItem.telephone','PropertyItem.business_no');
        $order = "PropertyItem.$sortname $sortorder";
        if($sortname == 'group_name'){
            $order = "PropertyGroup.$sortname $sortorder";
        }
        elseif($sortname == 'location_name' or $sortname == 'location_code'){
            $order = "Location.$sortname $sortorder";
        }
        elseif($sortname == 'type_name'){
            $order = "PropertyGroupType.$sortname $sortorder";
        }
        elseif($sortname == 'sub_type_name'){
            $order = "PropertyGroupSubType.$sortname $sortorder";
        }
        
        $propData = $this->PropertyItem->find('all', array(
            'contain'=>$contain ,
            'fields'=>$fields,
            'conditions' => $condition_array,
            'order' => $order,
            'limit'=>$limit,
            'offset'=>$start,
            'recursive' => 1
        ));
   
        
        $propCount  = $this->PropertyItem->find('count', array(
            'conditions' => $condition_array,
            'recursive' => -1
        ));
        
        $total_records = $propCount;
        
        if($propData){
            $return_arr = array();
            foreach ($propData as $obj){
                $fon =  $obj['PropertyItem']['telephone'];
                if(empty($fon)){
                    $fon =  $obj['PropertyItem']['business_no'];
                }

               $return_arr[] = array(
                    'id' => $obj['PropertyItem']['id'],
                    'cell' => array(
                        $obj['PropertyItem']['id'], 
                        $obj['PropertyGroup']['group_name'], 
                        $obj['Location']['location_name'],
                        $obj['PropertyItem']['loc_region'],
                        $obj['Location']['location_code'],
                        $obj['PropertyItem']['property_reg_no'], 
                        $obj['PropertyItem']['name'],
                        $fon,
                        $obj['PropertyGroupType']['type_name'], 
                        $obj['PropertyGroupSubType']['sub_type_name']
                    )
               );                  
            }
           return json_encode(array('success' => true, 'total'=>$total_records, 'page' => $page,'rows' => $return_arr));
        }
        else{
           return json_encode(array('success' => false, 'total'=>$total_records, 'page' => $page, 'rows' => array()));
        }	
         
   }
   
   
   /**
    * This get a property data
    * @name getProperty
    * @param void
    * @return Json Data
    * @access public
   */
   function getProperty(){  
		# disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false; 
		
		$ids = isset($_POST['ids']) ? json_decode($_POST['ids']) : 0;
        $propertyData = $this->PropertyItem->find('first',array(
            'conditions'=>array('PropertyItem.id'=>$ids, 'PropertyItem.deleted' => 0),
            'recursive' => 1
        ));
        
        if($propertyData){                
           return json_encode(array('code' => 0, 'data'=>$propertyData));
        }
        else{
           return json_encode(array('code' => 1, 'data'=> array()));
        }    
   }
   
   
   
    #Delete Users via ajax
    function deleteProperty(){
        $loggedUser =  $this->Session->read('userSessionData');
		if($this->request->is('ajax')){
			$this->autoRender = false;
			$this->autoLayout = false;
             
            $ids = $_POST['ids'];
            $items = ClassRegistry::init('PropertyItem');
            $result = $items->updateAll(
				array('PropertyItem.deleted' => 1 ), 
				array('PropertyItem.id' => $ids)
			);
			
			if($result){
				 echo json_encode(array('code' => 0, 'mesg' => 'Data successfully deleted'));
			}
			else{
				echo json_encode(array('code' => 1, 'mesg' => 'Data cannot be deleted'));
			}
         }
	}
       
    
    /**
    * @name Search Property
    * @param $id
    * @return Array
    * @access public
    */
   function searchProperty(){
      # Get the user session data
      $this->autoRender = false;
      $this->autoLayout = false;
      
      $text = strtolower($_GET['q']);
      $search_on = $_GET['search_on'];
      $text = mysql_real_escape_string($text);
      
      $result_set = $this->__getPropertyBySearch($text, $search_on);
      
      $data_array = array();
      foreach ($result_set as $row) {
         $key = $row['PropertyItem']['id'];
         $name = '';
         if(!empty($row['PropertyItem']['name'])){
            $name = $row['PropertyItem']['name'];
         }
         elseif(!empty($row['PropertyItem']['owners_name'])){
            $name = $row['PropertyItem']['owners_name'].' , '.$row['PropertyItem']['other_partners_name'];
         }
         elseif(!empty($row['PropertyItem']['other_partners_name'])){
            $name = $row['PropertyItem']['other_partners_name'].' , '.$row['PropertyItem']['owners_name'];
         }
         elseif(!empty($row['PropertyItem']['telephone'])){
            $name = $row['PropertyItem']['telephone'];
         }
         elseif(!empty($row['PropertyItem']['business_no'])){
            $name = $row['PropertyItem']['business_no'];
         }
         elseif(!empty($row['PropertyItem']['address'])){
            $name = $row['PropertyItem']['address'];
         }
         elseif(!empty($row['PropertyItem']['popular_area_name'])){
            $name = $row['PropertyItem']['popular_area_name'];
         }
         
         $value = $row['PropertyItem']['property_reg_no'].' ==> '.$name;                      
         $data_array[$key] = $value;
                   
      }
        
      foreach ($data_array as $key=>$value) {
    //	if (strpos(strtolower($key), $text) !== false) {
    		//echo "$key|$value\n";
            echo "$value|$key\n";
    //	}
      }
   }
   
   function __getPropertyBySearch($text, $search_on){
      # search condition
      $extra_fields = array();
      if($search_on == 'property_reg_no' or $search_on == 'telephone' or $search_on == 'business_no' or $search_on == 'address'){
         $conditions = array('OR' => array(
             "$search_on" => $text
         ));
         if($search_on == 'telephone'){
             $extra_fields[] = 'telephone';
         }
         elseif($search_on == 'business_no'){
             $extra_fields[] = 'business_no';
         }
         elseif($search_on == 'address'){
             $extra_fields[] = 'address';  
         }
         elseif($search_on == 'area_code'){
             $extra_fields[] = 'area_code';
         }
      }
      if($search_on == 'name'){
        $conditions = array('OR' => array(
             "$search_on LIKE" => $text . '%'
         ));
         
         $extra_fields[] = 'name'; 
      }
      if($search_on == 'owners_name'){
        $conditions = array('OR' => array(
             'owners_name LIKE' => $text . '%',
             'other_partners_name LIKE' => $text . '%',
        ));
        $extra_fields[] = 'owners_name';
        $extra_fields[] = 'other_partners_name';
      }
       if($search_on == 'popular_area_name'){
           $conditions = array('OR' => array(
               "$search_on LIKE" => $text . '%'
           ));

           $extra_fields[] = 'popular_area_name';
       }
      
      $fields  = array_merge(array('id', 'property_reg_no'),$extra_fields);
      return  $this->PropertyItem->find('all', array('conditions' => $conditions, 'fields' =>$fields, 'recursive' => -1));
   }
}
?>
